<template>
	<div class="components-container">
        <div class="header-form">
            <div class="layui-inline">
                <label>处理日期从</label>
                <el-date-picker  v-date v-model="selectData.ChddateGreaterAndEquals" type="date" placeholder="输入日期" @change="btnSearch"/>   
                 到 <el-date-picker  v-date v-model="selectData.ChddateLessAndEquals" type="date" placeholder="输入日期"  @change="btnSearch"/>  
            </div>
            <div class="layui-inline">
              <label class="layui-form-label">减免类型</label>
              <div v-if="!showAll" class="layui-input-inline">
                  <el-select v-model="selectData.RegiskeypointEquals" @change="ReductionType($event)"  placeholder="请选择减免类型">
                    <el-option v-if="this.isall" label="全部" :value="null" />
                    <el-option v-for="item in JMTypes" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
              </div>
              <!-- 嵊州减免类型问题 -->
              <div v-if="showAll" class="layui-input-inline">
                  <el-select v-model="selectData.RegiskeypointIn" multiple @change="ReductionType($event)"  placeholder="请选择减免类型">
                    <el-option v-for="item in JMTypes" :key="item.value" :label="item.label" :value="item.value" ></el-option>
                  </el-select>
              </div>
            </div>
            <div class="layui-inline" v-if="isshownb">
              <label class="layui-form-label">财政归属</label>
              <div class="layui-input-inline">
                <el-cascader :options="area" v-model="REGFINANCESBELONGEquals" filterable :show-all-levels="false" change-on-select @change="btnSearch"></el-cascader>
              </div>
            </div>
            
            <div class="layui-inline">
              <label class="layui-form-label" >统计地址</label>
              <div class="layui-input-inline">
                <el-cascader :options="area" v-model="AddIdOr" filterable :show-all-levels="false" change-on-select @change="btnSearch">
                </el-cascader>
              </div>
            </div>
            <el-button type="primary" @click="btnSearch" :disabled="downloadLoading" :loading="this.$store.state.isloading">搜索</el-button>
            <el-button :disabled="downloadLoading || this.$store.state.isloading"  @click="btnRepeat">重置</el-button>
        </div>
        <div style="margin-top:10px;">
          <ul class="toolList">
            <li v-if="btnShow(item.BTNVALUE)" v-for="(item, index) in $store.state.btnListCommon" @click="operate(item.BTNVALUE)">
              <el-button type="primary" :disabled="downloadLoading || $store.state.isloading" :value="item.BTNSHOWNAME" v-text="item.BTNSHOWNAME"></el-button> 
            </li>
            <li>
              <el-button type="primary" @click="exportExcel" :disabled="this.$store.state.isloading">导出Excel</el-button>
            </li>
          </ul>
        </div>
        <dataTable :headList="headList" v-if="hackReset == true" :dataList="dataList" :isIndex="true" :pageOrder="pageOrder" @pageChange="pageChange" @selectRow="selectRow" :hiddenColumn="hiddenColumn" :hiddenPageOrder="false" :height="height"></dataTable>
        <printmodal ref="printPdf"></printmodal>
        <h1 style="text-align:right;margin-right:100px;color:red;font-size:20px;">{{message}}</h1>
  </div>
</template>
<style rel="stylesheet/scss" lang="scss" scoped>
@import "src/styles/common.scss";
.el-button + .el-button {
  margin-left: 0;
}
.btn {
  text-align: center;
}
</style>
<script>
import dataTable from "@/components/Table/DataTable";
import printmodal from "@/components/Pdf/Print";
import apiBase from "@/api/apiBase.js";
import { formatDate, timeStringToDate } from "@/utils/date.js";
import { manage } from "@/mixins/managePage.js";
import { PRINT } from "@/components/Pdf/PDF.js";
import sweetModal from "@/components/sweetModal";

const INFO = "详情";
const EXPORT = "打印";

export default {
  name: "saleStatistics",
  mixins: [manage],
  data() {
    return {
      selectData: {
        RegcremationdateGreaterAndEquals: null,
        RegcremationdateLessAndEquals: null,
        //奉化个性化
        ChddateGreaterAndEquals: null,
        ChddateLessAndEquals: null,
        RegiskeypointEquals: null,
        RegiskeypointIn: [],
      },
      downloadLoading: false,
      OutDataExcel: [],
      height: "620",
      chargetype: [],
      JMTypes: [],
      isshownb:null,  //宁波控制显隐
      noDerate:'B',
      noDerateText:'不减免',
      title: null,
      order: null,
      message: null,
      hiddenColumn: false,
      area: [],
      AddIdOr: [],
      REGFINANCESBELONGEquals: [], //宁波财政归属
      istime: null,
      isall: null,
      showAll: null,
      hackReset: true,
    };
  },
  methods: {
    exportExcel() {
       if (this.dataList.length === 0) {
        this.$message.error("无导出数据！");
        return;
      }
      var startTime;
      var endTime;
      // if(!this.istime){
      //   if(this.selectData.RegcremationdateGreaterAndEquals){
      //     startTime = this.selectData.RegcremationdateGreaterAndEquals.toLocaleDateString();
      //   }else{
      //     startTime = '空';
      //   }
      //   if(this.selectData.RegcremationdateLessAndEquals){
      //     endTime = this.selectData.RegcremationdateLessAndEquals.toLocaleDateString();
      //   }else{
      //     endTime = '空';
      //   }
      // }else{
        if(this.selectData.ChddateGreaterAndEquals){
          startTime = this.selectData.ChddateGreaterAndEquals.toLocaleDateString();
        }else{
          startTime = '空';
        }
        if(this.selectData.ChddateLessAndEquals){
          endTime = this.selectData.ChddateLessAndEquals.toLocaleDateString();
        }else{
          endTime = '空';
        }
      // };
     
      let addrName = null;
      if(this.AddIdOr.length == 0){
        addrName = '全部';
      }else if(this.AddIdOr.length == 1){
        if(this.AddIdOr[0] === null){
          addrName = '全部';
        }else{
          for(var i = 0;i < this.area.length;i++){
            if(this.area[i].value == this.AddIdOr[0]){
              addrName = this.area[i].label;
            }
          }
        }
      }else if(this.AddIdOr.length == 2){
        var copyarea = this.area;
        // copyarea.splice(0,1);
        let addrId = this.AddIdOr[1];
        copyarea.forEach(function(value, index, arr) {
          value.children.forEach(function(v, i, a) {
            if (v.value == addrId) {
              addrName = v.label;
            }
          });
        });
      };
      if(this.isshownb ==true){
      let addrName1 = null;
      if(this.REGFINANCESBELONGEquals.length == 0){
        addrName1 = '全部';
      }else if(this.REGFINANCESBELONGEquals.length == 1){
        if(this.REGFINANCESBELONGEquals[0] === null){
          addrName1 = '全部';
        }else{
          for(var i = 0;i < this.area.length;i++){
            if(this.area[i].value == this.REGFINANCESBELONGEquals[0]){
              addrName1 = this.area[i].label;
            }
          }
        }
      }else if(this.REGFINANCESBELONGEquals.length == 2){
        var copyarea1 = this.area;
        // copyarea1.splice(0,1);
        let addrId = this.REGFINANCESBELONGEquals[1];
        copyarea1.forEach(function(value, index, arr) {
          value.children.forEach(function(v, i, a) {
            if (v.value == addrId) {
              addrName1 = v.label;
            }
          });
        });
      };
      }
     
      let headers = [];
      for(var i = 0;i < this.headList.length;i++){
        if(this.headList[i].ColumnChild == null){
            headers.push(this.headList[i]);
        }else{
          for(var s = 0;s <this.headList[i].ColumnChild.length;s++){
            headers.push(this.headList[i].ColumnChild[s]);
          }
        }
      }
      let data = [];
      apiBase.DoService(
        data,
        apiBase.getApiAdress().Param.GetIdvreductionHead,
        res => {
          this.downloadLoading = true;
          let headername;
          if(res.data.content == true){
            if(this.selectData.RegiskeypointEquals == 'A'){
              headername = '海曙区殡仪服务免费资金结算表（普通减免）' + '--' + addrName + '(' + startTime + '-' + endTime + ')';
            }else if(this.selectData.RegiskeypointEquals == 'B'){
              headername = '海曙区殡仪服务资金结算表（不减免）' + '--' + addrName + '(' + startTime + '-' + endTime + ')';
            }else{
              headername = '海曙区殡仪馆服务免费资金结算表（重点减免）' + '--' + addrName + '(' + startTime + '-' + endTime + ')';
            }
          }else{
            if(this.selectData.RegiskeypointEquals == 'A'){
              headername = localStorage.getItem('orgname') + '殡葬基本服务对象费用结算清册（普通减免）' + '--' + addrName + '(' + startTime + '-' + endTime + ')';
            }else if(this.selectData.RegiskeypointEquals == 'B'){
              headername = localStorage.getItem('orgname') + '殡葬基本服务对象费用结算清册（不减免）' + '--' + addrName + '(' + startTime + '-' + endTime + ')';
            }else{
              headername = localStorage.getItem('orgname') + '殡葬基本服务对象费用结算清册（重点减免）' + '--' + addrName + '(' + startTime + '-' + endTime + ')';
            }
          }
          headers.unshift({ColumnAlign:"center",ColumnChild:null,ColumnKey:"REGNAMEs",ColumnName:"序号",ColumnOrder:"REGNAMEs",ColumnWidth:"120"})
          for(var i = 0;i < this.OutDataExcel.length - 1;i++){
            this.OutDataExcel[i].REGNAMEs = i + 1;
          }
          require.ensure([], () => {
            const { export_json_to_excel } = require("@/vendor/Export2Excel");
            export_json_to_excel(
              headers,
              this.OutDataExcel,
              headername,
              undefined,
              "jmmxb"
            );
            this.downloadLoading = false;
          });
        }
      )
      
    },
    //功能操作
    operate(order) {
      this.order = order;
      this.dataRepeat();
      switch (this.order) {
        case EXPORT:
          this.$refs.printPdf.report(
            PRINT.PDFBASICSERSTATISTICS,
            this.getDataC()
          );
          break;
        default:
      }
    },
    //减免类型
    ReductionType(val){
      if(val == "A"){
        let data = {};
        apiBase.DoService(
          data,
          apiBase.getApiAdress().Column.GetBasicserStatisticsNolColumns,
          res => {
            this.headList = res.data.content;
          }
        );
      }else if(val == "B"){
        let data = {};
        apiBase.DoService(
          data,
          apiBase.getApiAdress().Column.GetBasicserStatisticsNoColumns,
          res => {
            this.headList = res.data.content;
          }
        );
      }else if(val == 'C'){
        let data = {};
        apiBase.DoService(
          data,
          apiBase.getApiAdress().Column.GetBasicserStatisticsPointColumns,
          res => {
            this.headList = res.data.content;
          }
        );
      }else if(val == 'D'){
        let data = {};
        this.hackReset = false;
        apiBase.DoService(
          data,
          apiBase.getApiAdress().Column.GetBasicserStatisticsYqColumns,
          res => {
            this.headList = res.data.content;
            this.$nextTick(() => {
              this.hackReset = true;
            })        
          }
        );
      }
      this.getData();
      this.getAllData();
      // this.$emit("refreshData");
    },
    getColumns() {
      let data = {};
        apiBase.DoService(
        data,
        apiBase.getApiAdress().Column.GetBasicserStatisticsColumns,
        res => {
          this.headList = res.data.content;
        }
      );
    },
    getDataC() {
      let Data = JSON.parse(JSON.stringify(this.selectData));
        Data.ChddateGreaterAndEquals = formatDate(
          Data.ChddateGreaterAndEquals,
          "yyyyMMdd"
        );
        Data.ChddateLessAndEquals = formatDate(
          Data.ChddateLessAndEquals,
          "yyyyMMdd"
        );
      if(this.AddIdOr.length != 0){
        Data.AddIdOr = this.AddIdOr[this.AddIdOr.length-1];
        if(Data.AddIdOr == '001'){
          Data.AddIdOr = null;
        }
      }else{
        Data.AddIdOr = null;
      }
      if(this.isshownb ==true){
        if(this.REGFINANCESBELONGEquals.length != 0){
        Data.REGFINANCESBELONGEquals = this.REGFINANCESBELONGEquals[this.REGFINANCESBELONGEquals.length-1];
        if(Data.REGFINANCESBELONGEquals == '001'){
          Data.REGFINANCESBELONGEquals = null;
        }
        }else{
          Data.REGFINANCESBELONGEquals = null;
        }
      }
      let data = {
        PageIndex: -1,
        PageSize: 100,
        OrderBy: this.pageOrder.orderType,
        OrderByType: this.pageOrder.orderSort,
        Data: Data
      };
      if(this.showAll){
        data.Data.RegiskeypointEquals = null
      }
      return data;
    },
    getData() {
      let Data = JSON.parse(JSON.stringify(this.selectData));
        Data.ChddateGreaterAndEquals = formatDate(
          Data.ChddateGreaterAndEquals,
          "yyyyMMdd"
        );
        Data.ChddateLessAndEquals = formatDate(
          Data.ChddateLessAndEquals,
          "yyyyMMdd"
        );
      if(this.AddIdOr.length != 0){
        Data.AddIdOr = this.AddIdOr[this.AddIdOr.length-1];
        if(Data.AddIdOr == '001'){
          Data.AddIdOr = null;
        }
      }else{
        Data.AddIdOr = null;
      }
      if(this.isshownb==true){
      if(this.REGFINANCESBELONGEquals.length != 0){
        Data.REGFINANCESBELONGEquals = this.REGFINANCESBELONGEquals[this.REGFINANCESBELONGEquals.length-1];
        if(Data.REGFINANCESBELONGEquals == '001'){
          Data.REGFINANCESBELONGEquals = null;
        }
      }else{
        Data.REGFINANCESBELONGEquals = null;
      }
      }
      let data = {
        PageIndex: 1,
        PageSize: 1000,
        OrderBy: this.pageOrder.orderType,
        OrderByType: this.pageOrder.orderSort,
        Data: Data
      };
      if(this.showAll){
        data.Data.RegiskeypointEquals = null
        apiBase.DoService(data,apiBase.getApiAdress().Report.QueryBasicserStatisticsNo,
              res => {
                this.dataList = res.data.content.OutData;
              });
      }else{
        if(Data.RegiskeypointEquals ==='B'){
          apiBase.DoService(data,apiBase.getApiAdress().Report.QueryBasicserStatisticsNo,
            res => {
              this.dataList = res.data.content.OutData;
            });
        }else if(Data.RegiskeypointEquals === null){
          apiBase.DoService(data,apiBase.getApiAdress().Report.QueryBasicserStatisticsNo,
              res => {
                this.dataList = res.data.content.OutData;
              });
        }else if(Data.RegiskeypointEquals==='A' || Data.RegiskeypointEquals==='C'){
          apiBase.DoService( data,apiBase.getApiAdress().Report.QueryBasicserStatistics,
            res => {
              this.dataList = res.data.content.OutData;
            });
        }else if(Data.RegiskeypointEquals ==='D'){
          apiBase.DoService( data,apiBase.getApiAdress().Report.QueryBasicserStatisticsYq,
            res => {
              this.dataList = res.data.content.OutData;
            });
        }else{
          console.log('出错了!');
        }
      }
      
    },
    getAllData() {
      let Data = JSON.parse(JSON.stringify(this.selectData));
        Data.ChddateGreaterAndEquals = formatDate(
          Data.ChddateGreaterAndEquals,
          "yyyyMMdd"
        );
        Data.ChddateLessAndEquals = formatDate(
          Data.ChddateLessAndEquals,
          "yyyyMMdd"
        );
      if(this.AddIdOr.length != 0){
        Data.AddIdOr = this.AddIdOr[this.AddIdOr.length-1];
        if(Data.AddIdOr == '001'){
          Data.AddIdOr = null;
        }
      }else{
        Data.AddIdOr = null;
      }
      if(this.isshownb ==true){
          if(this.REGFINANCESBELONGEquals.length != 0){
          Data.REGFINANCESBELONGEquals = this.REGFINANCESBELONGEquals[this.REGFINANCESBELONGEquals.length-1];
          if(Data.REGFINANCESBELONGEquals == '001'){
            Data.REGFINANCESBELONGEquals = null;
          }
          }else{
            Data.REGFINANCESBELONGEquals = null;
          }
      }
      let data = {
        PageIndex: -1,
        PageSize: 100,
        OrderBy: this.pageOrder.orderType,
        OrderByType: this.pageOrder.orderSort,
        Data: Data
      };
      if(this.showAll){
        data.Data.RegiskeypointEquals = null
        apiBase.DoService(data,apiBase.getApiAdress().Report.QueryBasicserStatisticsNo,
          res => {
            this.OutDataExcel = res.data.content.OutDataExcel;
            this.message = res.data.content.Message;
            this.pageOrder.totalNum = res.data.content.RecordCount;
          });
      }else{
        if(Data.RegiskeypointEquals==='B'){
          apiBase.DoService(data,apiBase.getApiAdress().Report.QueryBasicserStatisticsNo,
            res => {
              this.OutDataExcel = res.data.content.OutDataExcel;
              this.message = res.data.content.Message;
              this.pageOrder.totalNum = res.data.content.RecordCount;
            });
        }else if(Data.RegiskeypointEquals==null){
          apiBase.DoService(data,apiBase.getApiAdress().Report.QueryBasicserStatisticsNo,
              res => {
                this.OutDataExcel = res.data.content.OutDataExcel;
                this.message = res.data.content.Message;
                this.pageOrder.totalNum = res.data.content.RecordCount;
              });
        }else if(Data.RegiskeypointEquals==='A' || Data.RegiskeypointEquals==='C'){
          apiBase.DoService( data,apiBase.getApiAdress().Report.QueryBasicserStatistics,
            res => {
              this.OutDataExcel = res.data.content.OutDataExcel;
              this.message = res.data.content.Message;
              this.pageOrder.totalNum = res.data.content.RecordCount;
            });
        }else if(Data.RegiskeypointEquals ==='D'){
          apiBase.DoService( data,apiBase.getApiAdress().Report.QueryBasicserStatisticsYq,
            res => {
              this.OutDataExcel = res.data.content.OutDataExcel;
              this.message = res.data.content.Message;
              this.pageOrder.totalNum = res.data.content.RecordCount;
            });
        }
      }
    },
   
    getJM() {
      let data = {};
      apiBase.DoService(
        data,
        apiBase.getApiAdress().Code.GetKeyPointType,
        res => {
          let cdhTypeData = res.data.content,
            legendsCdhData = cdhTypeData.map(item => ({
              label: item.CodeName,
              value: item.CodeValue
            }));
          var JMType = legendsCdhData;
          this.JMTypes = legendsCdhData;
          this.selectData.RegiskeypointEquals = 'A';
        }
      );
    },
     //业务收费查询个性化
    GetBusinesschargeFH(){
      let data = {};
      apiBase.DoService(
        data,
        apiBase.getApiAdress().Param.GetBusinesschargeFH,
        res => {
          this.istime = res.data.content;
        }
      );
    },
    
    // 是否修改减免金额 
    GetIsModifyReduction(){
      let data = {};
      apiBase.DoService(
        data,
        apiBase.getApiAdress().Param.GetIsModifyReduction,
        res => {
          this.isall = res.data.content;
        }
      );
    },
    // 是否显示全部
    GetIsAllRedReport(){
      apiBase.DoService(
        {},
        apiBase.getApiAdress().Param.GetIsAllRedReport,
        res => {
          this.showAll = res.data.content;
        }
      );
    },
    getAddr() {
      let data = {};
      apiBase.DoService(
        data,
        apiBase.getApiAdress().Code.GetAddressMap,
        res => {
          let addData = res.data.content;
            let legendsAddData = addData.map(first => ({
              label: first.ADDNAME,
              value: first.ADDID,
              children: first.Children.map(second => ({
                label: second.ADDNAME,
                value: second.ADDID
              }))
            }));
            this.area = legendsAddData;
            // this.area.unshift({label:'全部',value: null});
             this.area.unshift({label:'全部',value: '001',children:[{label: '全部',value: null}]});
        }
      );
    },
    btnSearch(){
      this.getData();
      this.getAllData();
      this.$store.state.isloading = true;
    },
    //查询条件重置
    btnRepeat() {
      this.selectData = {
        //奉化个性化
        ChddateGreaterAndEquals: null,
        ChddateLessAndEquals: null,
        RegiskeypointEquals: null,
        RegiskeypointIn: [],
      };
      //奉化
      this.selectData.ChddateGreaterAndEquals = new Date();
      this.selectData.ChddateGreaterAndEquals.setDate(1);
      this.selectData.ChddateLessAndEquals = new Date();
      var day = new Date();
      var year = day.getFullYear();
      var month = day.getMonth() + 1;
      var d = new Date(year, month, 0);
      var dat = d.getDate();
      //奉化
      this.selectData.ChddateLessAndEquals.setDate(dat);
      this.selectData.RegiskeypointEquals = 'A';
      this.ReductionType('A');
      this.AddIdOr = [];
      this.REGFINANCESBELONGEquals = [];
      // this.getData();
    },
    //宁波个性化
    Getisshownb(){
     //火化登记是否显示c财政归属(宁波)
      apiBase.DoService(
        {},
        apiBase.getApiAdress().Param.GetIsShowREGFinancesBelong,
        res => {
          this.isshownb = res.data.content;
        });
    },
    btnShow(btn) {
      switch (btn) {
        case EXPORT:
          return true;
          break;
        default:
          return false;
      }
    },
    //数据重置
    dataRepeat() {}
  },
  mounted() {},
  components: {
    dataTable,
    sweetModal,
    printmodal
  },
  //当前选中行
  selectRow(row) {
    this.currentRow = row;
    this.$emit("selectRow", row, "");
  },
  created() {
    //奉化
    this.selectData.ChddateGreaterAndEquals = new Date();
    this.selectData.ChddateGreaterAndEquals.setDate(1);
    this.selectData.ChddateLessAndEquals = new Date();

    var day = new Date();
    var year = day.getFullYear();
    var month = day.getMonth() + 1;
    var d = new Date(year, month, 0);
    var dat = d.getDate();
    //奉化
    this.selectData.ChddateLessAndEquals.setDate(dat);
    this.getColumns();
    setTimeout(() => {
      this.getData();
      this.getAllData();
    },500);
    this.$nextTick(()=>{
      this.getJM();
    })
    this.getAddr();
    this.GetBusinesschargeFH();
    this.GetIsModifyReduction();
    this.GetIsAllRedReport()
    this.Getisshownb();
  }
};
</script>